package models

import (
	"errors"
	"log"
	"time"

	"2021-06-12/tools"

	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

// WeAppUser 微信用户
type WeAppUser struct {
	OpenId    string `json:"openId"`
	NickName  string `json:"nickname"`
	Gender    int    `json:"gender"`
	AvatarURL string `json:"avatarUrl"`
}

type PhoneInfo struct {
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	CountryCode     string `json:"countryCode"`
}

// User 用户
type User struct {
	Id           string    `orm:"column(Id)" json:"id"`
	OpenId       string    `orm:"pk;column(OpenId)" json:"openId"`
	UnionId      string    `orm:"column(UnionId)" json:"unionId"`
	AccessToken  string    `orm:"column(AccessToken)" json:"accessToken"`
	CREATED_TIME time.Time `orm:"column(CREATED_TIME)" json:"created_time"`
	UPDATED_TIME time.Time `orm:"column(UPDATED_TIME)" json:"updated_time"`
	NickName     string    `orm:"column(NickName)" json:"nickname"`
	Gender       int       `orm:"column(Gender)" json:"gender"`
	AvatarURL    string    `orm:"column(AvatarURL)" json:"avatarUrl"`
	Code         string    `orm:"column(Code)" json:"code"`
	ReferCode    string    `orm:"column(ReferCode)" json:"referCode"`
	Sessionkey   string    `orm:"column(Sessionkey)" json:"sessionKey"`
	Phone        string    `orm:"column(Phone)" json:"phone"`
	Rewards      string    `orm:"column(Rewards)" json:"rewards"`
	ReferNum     int       `orm:"column(ReferNum)" json:"referNum"`
	Label        string    `orm:"column(Label)" json:"label"`
}

//验证用户信息
func checkUser(u *User) (err error) {
	valid := validation.Validation{}
	b, _ := valid.Valid(&u)
	if !b {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
			return errors.New(err.Message)
		}
	}
	return nil
}

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)
	orm.RegisterModel(new(User))

}

//添加用户
func AddUser(u *User) (int64, error) {
	if err := checkUser(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	user := new(User)
	uid := tools.GenUid()
	user.Id = uid                  // id
	user.OpenId = u.OpenId         // openid
	user.CREATED_TIME = time.Now() // created_time
	user.Code = string(tools.CreateCode())

	id, err := o.Insert(user)
	return id, err
}

//更新用户信息
func UpdateUserForUserInfo(u *User) (int64, error) {
	if err := checkUser(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	user := make(orm.Params)
	if len(u.NickName) > 0 {
		user["NickName"] = u.NickName

	}
	if u.Gender > 0 {
		user["Gender"] = u.Gender
	}
	if len(u.AvatarURL) > 0 {
		user["AvatarURL"] = u.AvatarURL
	}
	user["UPDATED_TIME"] = time.Now()

	if len(user) == 0 {
		return 0, errors.New("update field is empty")
	}
	var table User
	num, err := o.QueryTable(table).Filter("OpenId", u.OpenId).Update(user)
	return num, err
}

//更新用户手机号
func UpdateUserForPhone(u *User) (int64, error) {
	if err := checkUser(u); err != nil {
		return 0, err
	}
	o := orm.NewOrm()
	user := make(orm.Params)
	if len(u.Phone) > 0 {
		user["Phone"] = u.Phone
	}

	if len(user) == 0 {
		return 0, errors.New("update field is empty")
	}
	var table User
	num, err := o.QueryTable(table).Filter("OpenId", u.OpenId).Update(user)
	return num, err
}

func GetUserByOpenId(openId string) (User, error) {
	user := User{OpenId: openId}
	o := orm.NewOrm()
	err := o.Read(&user)
	if err != nil {
		return user, err
	}
	return user, err
}

func GetUserByCode(code string) (User, error) {
	user := User{Code: code}
	o := orm.NewOrm()
	err := o.Read(&user, "Code")
	return user, err
}
